import {
  delReference,
  getReference,
  mainPointGenerate,
} from '@/services/ant-design-pro/highClassWrite';
import { CloseOutlined } from '@ant-design/icons';
import { connect } from '@umijs/max';
import { message, Tabs, TabsProps } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import './index.less';

const ReferenceSpace: React.FC<any> = forwardRef((props, ref) => {
  const [tabKey, setTabKey] = useState<string>('1');
  const [points, setPoints] = useState<any[]>([]);
  const [materials, setMaterials] = useState<any[]>([]);
  const [contents, setContents] = useState<any[]>([]);
  //预留触发更新数据
  const updateData = (params: any) => {
    console.log(params);
    const type = +params === 1 ? '观点资料' : +params === 2 ? '结构资料' : '内容资料';
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    refreshData(type);
  };

  //预留触发的方法
  useImperativeHandle(ref, () => ({
    updateData,
  }));

  const refreshData = async (type: string) => {
    if (!props.highClassWrite.writing_session_id) return;
    const params: any = {
      writing_session_id: props.highClassWrite.writing_session_id,
      material_type: type,
    };
    const res = await getReference(params);
    if (res.code === 0) {
      const { materials } = res.data;
      if (type === '观点资料') {
        setPoints([...materials]);
      } else if (type === '内容资料') {
        setContents([...materials]);
      } else if (type === '结构资料') {
        setMaterials([...materials]);
      }
    } else {
      message.error(res.msg);
    }
  };

  useEffect(() => {
    setTimeout(() => {
      updateData(1);
    }, 10);
  }, [props.highClassWrite.writing_session_id]);

  // 更新大纲
  const updateOutline = async () => {
    // 生成大纲
    const res: any = await mainPointGenerate({
      write_session_id: props.highClassWrite.writing_session_id,
    });
    if (res.code === 0) {
      // 拉取大纲
      props.triggerArticleMain({});
    } else {
      message.error(res.msg);
    }
  };

  const delPoint = async (i: number, type: string, id: any) => {
    const res = await delReference({ id });
    if (res.code === 0) {
      if (type === 'point') {
        const point_copy = [...points];
        point_copy.splice(i, 1);
        setPoints(point_copy);
        updateOutline();
      } else if (type === 'material') {
        const material_copy = [...materials];
        material_copy.splice(i, 1);
        setMaterials(material_copy);
        updateOutline();
      } else if (type === 'content') {
        const content_copy = [...contents];
        content_copy.splice(i, 1);
        setContents(content_copy);
      }
    } else {
      message.error(res.msg);
    }
  };

  const item = (point: any, i: number, type: string) => {
    return (
      <div key={i} className="reference__point-item">
        <div className="reference__point-item-content">
          <div className="m-r-10">{i + 1}、</div>
          <div
            dangerouslySetInnerHTML={{
              __html: point.main_body
                .split('\n')
                .map((paragraph: any) => `<p>${paragraph}</p>`)
                .join(''),
            }}
          ></div>
        </div>
        <div
          className="reference__point-item-delete"
          onClick={(e) => {
            e.stopPropagation();
            delPoint(i, type, point.id);
          }}
        >
          <CloseOutlined />
        </div>
      </div>
    );
  };

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: '观点资料',
      children: (
        <div>
          {points.length > 0 && (
            <div className="reference__point">
              <div className="reference__point-title">
                <span className="reference__point-dot"></span>
                <span>观点资料</span>
              </div>
              {points.map((point: any, i: number) => {
                return item(point, i, 'point');
              })}
            </div>
          )}
          {!points.length && (
            <div style={{ color: 'rgba(62, 67, 82, .5)', fontSize: '12px' }}>暂无观点资料</div>
          )}
        </div>
      ),
    },
    {
      key: '2',
      label: '结构资料',
      children: (
        <div>
          {materials.length > 0 && (
            <div className="reference__point">
              <div className="reference__point-title blue">
                <span className="reference__point-dot blue"></span>
                <span>结构资料</span>
              </div>
              {materials.map((material: any, i: number) => {
                return item(material, i, 'material');
              })}
            </div>
          )}
          {!materials.length && (
            <div style={{ color: 'rgba(62, 67, 82, .5)', fontSize: '12px' }}>暂无结构资料</div>
          )}
        </div>
      ),
    },
    {
      key: '3',
      label: '内容资料',
      children: (
        <div>
          {contents.length > 0 && (
            <div className="reference__point">
              <div className="reference__point-title green">
                <span className="reference__point-dot green"></span>
                <span>内容资料</span>
              </div>
              {contents.map((content: any, i: number) => {
                return item(content, i, 'content');
              })}
            </div>
          )}
          {!contents.length && (
            <div style={{ color: 'rgba(62, 67, 82, .5)', fontSize: '12px' }}>暂无内容资料</div>
          )}
        </div>
      ),
    },
  ];

  const tabChange = (value: string) => {
    // tabKey.current = value;
    setTabKey(value);
    updateData(value);
  };

  return (
    <div className="referenceSpaceWrap">
      <div className="title">参考空间</div>
      <Tabs
        className="tab"
        defaultActiveKey=""
        items={items}
        activeKey={tabKey}
        onChange={tabChange}
      ></Tabs>
    </div>
  );
});

export default connect(({ highClassWrite }) => ({ highClassWrite }), null, null, {
  forwardRef: true,
})(ReferenceSpace);
